package com.javasee.rain.stock.service;

import com.javasee.rain.stock.mapper.ActionFieldMapper;
import com.javasee.rain.stock.model.ActionField;
import com.javasee.rain.stock.model.StockActionInfo;
import com.javasee.rain.stock.model.ArticleInfo;
import com.javasee.rain.stock.model.ActionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 异动解析服务类
 * 
 * @author : xinyanfei
 * @date : 2025/10/10
 * Copyright (c) 2025, 京东商城 All Rights Reserved.
 */
@RestController
@RequestMapping("/api/action")
@CrossOrigin(origins = "*") // 允许跨域访问
public class ActionService {

    @Autowired
    private ActionFieldMapper actionFieldMapper;

    /**
     * 根据日期获取异动解析数据
     * 
     * @param date 查询日期
     * @return 异动解析数据
     */
    @GetMapping("/{date}")
    public ResponseEntity<List<ActionField>> getActionByDate(@PathVariable String date) {
        try {
            // 先查询基础领域数据
            List<ActionField> actionFields = actionFieldMapper.selectByDate(date);
            
            // 为每个领域填充详细的股票异动信息并构建树状结构
            for (ActionField field : actionFields) {
                List<StockActionInfo> stockList = getStockActionDetails(date, field.getActionFieldId());
                field.setList(stockList);
                field.setCount(stockList.size());
                
                // 构建子节点（股票节点）
                List<ActionField> children = new ArrayList<>();
                for (StockActionInfo stock : stockList) {
                    ActionField stockNode = new ActionField();
                    stockNode.setActionFieldId(stock.getCode()); // 使用股票代码作为ID
                    
                    // 构建股票名称：股票名称 + 代码 + 连板信息
                    StringBuilder stockName = new StringBuilder();
                    stockName.append(stock.getName())
                            .append(" (")
                            .append(stock.getCode())
                            .append(")");
                    
                    // 添加连板信息到股票名称中
                    if (stock.getArticle() != null && stock.getArticle().getActionInfo() != null) {
                        ActionInfo actionInfo = stock.getArticle().getActionInfo();
                        if (actionInfo.getNum() != null && !actionInfo.getNum().isEmpty()) {
                            stockName.append(" [")
                                    .append(actionInfo.getNum())
                                    .append("]");
                        }
                    }
                    
                    stockNode.setName(stockName.toString());
                    stockNode.setCount(1);
                    stockNode.setList(Arrays.asList(stock)); // 每个股票节点包含自己的详细信息
                    stockNode.setChildren(new ArrayList<>()); // 股票节点没有子节点
                    children.add(stockNode);
                }
                field.setChildren(children);
            }

            System.out.println("异动解析数据查询成功，记录数: " + actionFields.size());
            return ResponseEntity.ok(actionFields);
        } catch (Exception e) {
            System.err.println("查询异动解析数据失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取所有异动解析数据
     * 
     * @return 异动解析数据
     */
    @GetMapping("/get")
    public ResponseEntity<Map<String, Object>> getAllAction() {
        try {
            List<ActionField> actionFields = actionFieldMapper.selectAll();
            
            // 为每个领域填充详细的股票异动信息
            for (ActionField field : actionFields) {
                List<StockActionInfo> stockList = getStockActionDetails(field.getDate(), field.getActionFieldId());
                field.setList(stockList);
                field.setCount(stockList.size());
            }

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功");
            response.put("data", actionFields);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("获取异动解析数据失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 获取指定日期和领域的股票异动详细信息
     * 
     * @param date 日期
     * @param actionFieldId 领域ID
     * @return 股票异动信息列表
     */
    private List<StockActionInfo> getStockActionDetails(String date, String actionFieldId) {
        List<StockActionInfo> result = new ArrayList<>();
        
        try {
            System.out.println("获取股票异动详细信息，日期: " + date + ", 领域ID: " + actionFieldId);
            
            // 查询数据库获取原始数据
            List<Map<String, Object>> rawData = actionFieldMapper.selectActionDetailsByDateAndField(date, actionFieldId);
            
            // 将原始数据转换为结构化的对象
            Map<String, StockActionInfo> stockMap = new HashMap<>();
            
            for (Map<String, Object> row : rawData) {
                String code = (String) row.get("code");
                String stockName = (String) row.get("stock_name");
                
                // 如果这个股票还没有创建，先创建
                if (!stockMap.containsKey(code)) {
                    StockActionInfo stockInfo = new StockActionInfo();
                    stockInfo.setCode(code);
                    stockInfo.setName(stockName);
                    stockInfo.setArticle(new ArticleInfo());
                    stockMap.put(code, stockInfo);
                }
                
                // 填充文章和异动信息
                StockActionInfo stockInfo = stockMap.get(code);
                ArticleInfo articleInfo = stockInfo.getArticle();
                
                // 设置文章基本信息
                articleInfo.setArticleId((String) row.get("article_id"));
                articleInfo.setCommentCount(row.get("comment_count") != null ? (Integer) row.get("comment_count") : 0);
                articleInfo.setLikeCount(row.get("like_count") != null ? (Integer) row.get("like_count") : 0);
                articleInfo.setCreateTime((String) row.get("article_create_time"));
                articleInfo.setUserId((String) row.get("user_id"));
                articleInfo.setForwardCount(row.get("forward_count") != null ? (Integer) row.get("forward_count") : 0);
                articleInfo.setStepCount(row.get("step_count") != null ? (Integer) row.get("step_count") : 0);
                articleInfo.setTitle((String) row.get("title"));
                articleInfo.setIsStep(row.get("is_step") != null ? (Integer) row.get("is_step") : 0);
                
                // 设置异动详细信息
                ActionInfo actionInfo = new ActionInfo();
                actionInfo.setArticleId((String) row.get("article_id"));
                actionInfo.setActionInfoId((String) row.get("action_info_id"));
                actionInfo.setStockId((String) row.get("stock_id"));
                actionInfo.setActionFieldId((String) row.get("action_field_id"));
                actionInfo.setTime((String) row.get("time"));
                actionInfo.setNum((String) row.get("num"));
                actionInfo.setPrice(row.get("price") != null ? ((Number) row.get("price")).doubleValue() : null);
                actionInfo.setDay(row.get("day") != null ? (Integer) row.get("day") : null);
                actionInfo.setEdition(row.get("edition") != null ? (Integer) row.get("edition") : null);
                actionInfo.setSharesRange(row.get("shares_range") != null ? ((Number) row.get("shares_range")).doubleValue() : null);
                actionInfo.setExpound((String) row.get("expound"));
                actionInfo.setIsCrawl(row.get("is_crawl") != null ? (Integer) row.get("is_crawl") : 0);
                actionInfo.setIsRecommend(row.get("is_recommend") != null ? (Integer) row.get("is_recommend") : 0);
                actionInfo.setCreateTime((String) row.get("action_create_time"));
                actionInfo.setUpdateTime((String) row.get("action_update_time"));
                actionInfo.setSortNo(row.get("action_sort_no") != null ? (Integer) row.get("action_sort_no") : 0);
                
                articleInfo.setActionInfo(actionInfo);
            }
            
            result = new ArrayList<>(stockMap.values());
            System.out.println("成功获取股票异动详细信息，数量: " + result.size());
            
        } catch (Exception e) {
            System.err.println("获取股票异动详细信息失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }
}